<template>
  <div class="upload-container">
    <div class="upload-box" v-if="!uploadData.length">
      <a-upload-dragger
          v-model:fileList="fileList"
          name="file"
          accept=".xlsx,.csv,.xls"
          :multiple="false"
          :customRequest="handleCustomRequest"
          :show-upload-list="false"
          @change="handleChange"
          @drop="handleDrop"
      >
        <p class="ant-upload-drag-icon">
          <inbox-outlined></inbox-outlined>
        </p>
        <p class="ant-upload-text">点击或拖动文件至此区域上传</p>
      </a-upload-dragger>
      <div style="text-align: center;">
        <p class="ant-upload-hint">
          下载模板
          <a target="_blank" href="/static/表头.xlsx">表头.xlsx</a>
        </p>
      </div>
    </div>
    <div v-else>
      <a-card>
        <a-table :pagination="false" :dataSource="uploadData" :columns="uploadColumns">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'fileList'">
              <a-upload v-model:file-list="record.fileList"
                        :max-count="1"
                        accept=".mp3,.wav,.ogg"
                        :before-upload="(file) =>beforeUpload(file,record)" @remove="(file) => handleRemove(file,record)">
                <a-button>
                  <UploadOutlined></UploadOutlined>
                  选择录音文件
                </a-button>
              </a-upload>
            </template>
          </template>
        </a-table>
        <a-space style="padding-top: 20px;">
          <a-button :loading="loading" type="primary" @click="onSubmit">批量提交</a-button>
          <a-button style="margin-left: 10px" @click="resetForm">清空</a-button>
        </a-space>
      </a-card>
    </div>
  </div>

</template>
<script setup lang="ts">
import {ref} from 'vue';
import {InboxOutlined, UploadOutlined} from '@ant-design/icons-vue';
import {message} from 'ant-design-vue';
import type {UploadChangeParam} from 'ant-design-vue';
import * as XLSX from 'xlsx';
import dayjs from "dayjs";
import {useClueStore} from "@/stores/clue";
import {useSettingStore} from "@/stores/setting";

const settingStore = useSettingStore();
const clueStore = useClueStore();
const fileList = ref([]);
const uploadData = ref([]);
const loading = ref(false);
const uploadColumns = ref([
  {
    title: "日期",
    dataIndex: "date",
    key: "date",
  }, {
    title: "客户姓名",
    dataIndex: "name",
    key: "name",
  }, {
    title: "客户号码",
    dataIndex: "phone",
    key: "phone",
  }, {
    title: "所在地区",
    dataIndex: "address",
    key: "address",
  }, {
    title: "跟进记录",
    dataIndex: "remark",
    key: "remark",
  }, {
    title: "录音文件",
    dataIndex: "fileList",
    key: "fileList",
  }, {
    title: "验证结果",
    dataIndex: "validated",
    key: "validated",
  },
])
const handleChange = (info: UploadChangeParam) => {
  const status = info.file.status;
  if (status !== 'uploading') {
    console.log(info.file, info.fileList);
  }
  if (status === 'done') {
    message.success(`${info.file.name} file uploaded successfully.`);
  } else if (status === 'error') {
    message.error(`${info.file.name} file upload failed.`);
  }
};

function handleDrop(e: DragEvent) {
  console.log(e);
}


const handleRemove = (file: any, record: any) => {
  const index = record.fileList.indexOf(file);
  const newFileList = record.fileList.slice();
  newFileList.splice(index, 1);
  record.fileList = newFileList;
};

const beforeUpload = (file: any, record: any) => {
  record.fileList = [...(record.fileList || []), file];
  return false;
};

const readFile = async (file: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e: any) => {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, {type: 'array'});
      const sheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[sheetName];
      const jsonData = XLSX.utils.sheet_to_json(worksheet, {header: 1});
      resolve(jsonData);
    };
    reader.onerror = (error) => reject(error);
    reader.readAsArrayBuffer(file);
  });
}

const validateExcelConfig = () => {
  const headers = settingStore.setting.headers;
  if (!headers.length) return false;
  const fields = ["date_field", "name_field", "phone_field", "remark_field"]
  for (const field of fields) {
    if (!headers.includes(settingStore.setting[field])) return false;
  }
  return true;
}

const handleCustomRequest = async ({file}: any) => {
  try {
    if (!validateExcelConfig()) {
      message.error("数据配置未完成,请先配置 excel 数据");
      return;
    }
    // Step 1: 读取文件内容
    const fileData = await readFile(file);
    console.log("fileData", fileData);

    // Step 2: 验证数据
    const isValid = validateData(fileData);
    if (!isValid) {
      message.error("数据验证失败，请检查文件内容");
      return;
    }
    const result = processData(fileData);
    uploadData.value = result;
    message.success("文件读取并处理成功！");
  } catch (error: any) {
    console.error("error", error);
    message.error("文件处理失败：" + error.message);
  }
}

const validateData = (data: any) => {
  // const headers = ["日期", "客户姓名", "电话", "跟进一"];
  const headers = settingStore.setting.headers;

  const firstRow = data[0];
  console.log("firstRow", firstRow);
  if (!firstRow || headers.some((header: any) => !firstRow.includes(header))) {
    return false;
  }

  return true;
}

const processData = (data: any) => {
  const firstRow = data[0];
  const {date_field, name_field, phone_field, remark_field, address_field} = settingStore.setting;
  return data.slice(1).map((row: any) => {
    const item: any = {};
    for (let i = 0; i < firstRow.length; i++) {
      const key = firstRow[i];
      item[key] = row[i];
    }
    const dateCell = item[date_field];

    // 日期解析
    const validate = []

    let date = null;
    if (typeof dateCell === 'number') {
      date = dayjs(XLSX.SSF.format("yyyy-mm-dd hh:mm:ss", dateCell)).format("YYYY-MM-DD HH:mm:ss");
    } else if (dayjs(dateCell, "YYYY-MM-DD", true).isValid()) {
      date = dayjs(dateCell).format("YYYY-MM-DD HH:mm:ss");
    } else {
      validate.push("无效日期");
    }

    // 手机号验证
    const phonePattern = /^1[3-9]\d{9}$/;
    const phone = item[phone_field];
    const phoneValid = phonePattern.test(phone);
    if (!phoneValid)
      validate.push("无效号码");

    return {
      date: date,
      phone: phone,
      name: item[name_field] || '无名',
      address: item[address_field] || '',
      remark: item[remark_field] || '无跟进记录',
      fileList: [],
      validated: validate.join("，") || "有效",
    }
  }).filter((item: any) => (item.phone));
}

const resetForm = () => {
  uploadData.value = [];
}

const onSubmit = async () => {
  const data = uploadData.value.filter((item: any) => (item.validated === '有效'))
  if (!data.length) {
    message.info("没有有效数据")
    return;
  }
  if (loading.value) return;
  loading.value = true;
  let c_list = [];
  for (const item of uploadData.value) {
    if (item.validated === '有效') {
      try {
        console.log("item", item);
        const r = await clueStore.postApi(item);
        if (r) continue;
      } catch (e) {
        console.error("e", e);
      }
    }
    c_list.push(item);
  }
  uploadData.value = c_list;
  loading.value = false;
}
</script>
<style scoped lang="less">
.upload-container {
  padding: 50px;
}

.upload-box {
  width: 50%;
  margin: 0 auto;
}
</style>
